package com.school.sports.controller;

import com.school.sports.common.Result;
import com.school.sports.entity.ExceptionRecord;
import com.school.sports.service.ExceptionHandlingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 异常管理控制器
 * 提供异常记录的管理功能
 *
 * @author 系统开发团队
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/exception-management")
@Tag(name = "异常管理", description = "异常记录管理相关接口")
public class ExceptionManagementController {

    @Autowired(required = false)
    private ExceptionHandlingService exceptionHandlingService;

    /**
     * 获取异常统计信息
     */
    @Operation(summary = "获取异常统计", description = "获取系统中异常记录的统计信息")
    @GetMapping("/statistics")
    @PreAuthorize("hasRole('管理员')")
    public Result<Map<String, Object>> getExceptionStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();

            if (exceptionHandlingService != null) {
                long severeCount = exceptionHandlingService.getSevereExceptionCount();
                long pendingCount = exceptionHandlingService.getPendingExceptionCount();

                statistics.put("severeCount", severeCount);
                statistics.put("pendingCount", pendingCount);
                statistics.put("timestamp", LocalDateTime.now());
                statistics.put("message", "统计信息获取成功");
            } else {
                statistics.put("message", "异常处理服务未启用");
                statistics.put("severeCount", 0);
                statistics.put("pendingCount", 0);
            }

            return Result.success("获取统计信息成功", statistics);
        } catch (Exception e) {
            log.error("获取异常统计信息失败：{}", e.getMessage());
            return Result.error("获取统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 手动清理历史异常
     */
    @Operation(summary = "清理历史异常", description = "手动清理系统中的历史异常记录")
    @PostMapping("/cleanup")
    @PreAuthorize("hasRole('管理员')")
    public Result<String> cleanupExceptions(
            @Parameter(description = "清理天数，默认7天", required = false)
            @RequestParam(defaultValue = "7") int days) {
        try {
            if (exceptionHandlingService == null) {
                return Result.error("异常处理服务未启用");
            }

            LocalDateTime beforeTime = LocalDateTime.now().minusDays(days);
            int cleanedCount = exceptionHandlingService.cleanExpiredExceptionRecords(beforeTime);

            String message = String.format("成功清理 %d 天前的已处理异常记录 %d 条", days, cleanedCount);
            log.info("管理员手动清理异常记录：{}", message);

            return Result.success(message);
        } catch (Exception e) {
            log.error("清理历史异常失败：{}", e.getMessage());
            return Result.error("清理失败：" + e.getMessage());
        }
    }

    /**
     * 忽略所有待处理异常
     */
    @Operation(summary = "忽略待处理异常", description = "将所有待处理异常标记为已忽略")
    @PostMapping("/ignore-pending")
    @PreAuthorize("hasRole('管理员')")
    public Result<String> ignorePendingExceptions() {
        try {
            if (exceptionHandlingService == null) {
                return Result.error("异常处理服务未启用");
            }

            // 这里可以调用服务层的方法来忽略待处理异常
            // 由于当前服务接口没有这个方法，我们返回操作说明
            log.info("管理员请求忽略所有待处理异常");

            return Result.success("忽略待处理异常操作已执行，请查看日志了解详细信息");
        } catch (Exception e) {
            log.error("忽略待处理异常失败：{}", e.getMessage());
            return Result.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 获取系统健康状态
     */
    @Operation(summary = "系统健康检查", description = "获取系统健康状态信息")
    @GetMapping("/health")
    @PreAuthorize("hasRole('管理员')")
    public Result<Map<String, Object>> getSystemHealth() {
        try {
            Map<String, Object> health = new HashMap<>();

            if (exceptionHandlingService != null) {
                long severeCount = exceptionHandlingService.getSevereExceptionCount();
                long pendingCount = exceptionHandlingService.getPendingExceptionCount();

                // 判断系统健康状态
                String status = "健康";
                if (severeCount > 0) {
                    status = "警告";
                } else if (pendingCount > 50) {
                    status = "注意";
                }

                health.put("status", status);
                health.put("severeExceptions", severeCount);
                health.put("pendingExceptions", pendingCount);
                health.put("checkTime", LocalDateTime.now());
                health.put("exceptionServiceEnabled", true);
            } else {
                health.put("status", "异常服务未启用");
                health.put("severeExceptions", 0);
                health.put("pendingExceptions", 0);
                health.put("checkTime", LocalDateTime.now());
                health.put("exceptionServiceEnabled", false);
            }

            return Result.success("系统健康状态", health);
        } catch (Exception e) {
            log.error("获取系统健康状态失败：{}", e.getMessage());
            return Result.error("获取健康状态失败：" + e.getMessage());
        }
    }
}